package com.mspbots.core.wise.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.wise.mapper.TenantCompaniesMapper;
import com.mspbots.core.wise.model.TenantCompanies;
import com.mspbots.core.wise.service.TenantCompaniesService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Jay Yang
 */
@Service
public class TenantCompaniesServiceImpl extends AbstractBaseServiceImpl<TenantCompaniesMapper, TenantCompanies> implements TenantCompaniesService {
    @Override
    public List<TenantCompanies> getCompaniesList(TenantCompanies q) {
        Set<TenantCompanies> companiesSet = this.baseMapper.getCompaniesList(q);
        if (!StringUtils.isEmpty(q.getCompanyIds())) {
            List<Integer> cwIds = Arrays.stream(StringUtils.commaDelimitedListToStringArray(q.getCompanyIds()))
                    .map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
            List<TenantCompanies> list = super.list(Wrappers.<TenantCompanies>lambdaQuery()
                    .eq(TenantCompanies::getTenantId, q.getTenantId())
                    .in(TenantCompanies::getCwId, cwIds)
                    .select(TenantCompanies::getCwId, TenantCompanies::getName));
            Optional.ofNullable(list).ifPresent(companiesSet::addAll);
        }
        List<TenantCompanies> companiesList = new ArrayList<>(companiesSet);
        companiesList.sort(Comparator.comparing(TenantCompanies::getName));
        return companiesList;
    }
}
